﻿namespace ContactsSync.Providers.Twitter
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.Reflection;
    using ContactsSync.Infrastructure.Models;
    using Dimebrain.TweetSharp;
    using Dimebrain.TweetSharp.Core.Web;
    using Dimebrain.TweetSharp.Extensions;
    using Dimebrain.TweetSharp.Fluent;
    using Dimebrain.TweetSharp.Model;
    using Microsoft.Practices.Composite.Events;

    public class TwitterContactsProvider : IContactsProvider
    {
        private readonly string username;
        private readonly string password;

        public TwitterContactsProvider()
        {
            string path = Path.Combine("Modules", Assembly.GetExecutingAssembly().ManifestModule.Name);
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(path);

            this.username = configuration.AppSettings.Settings["user"].Value;
            this.password = configuration.AppSettings.Settings["password"].Value;
        }

        public event EventHandler<DataEventArgs<IList<Contact>>> RetrieveContactsCompleted;

        public string ProviderName
        {
            get { return "Twitter"; }
        }

        public void RetrieveContactsAsync()
        {
            TwitterClientInfo clientInfo = new TwitterClientInfo
                                               {
                                                   ClientName = "ContactsSync",
                                                   ClientUrl = "http://www.renzi.com.ar/",
                                                   ClientVersion = "0.0.0.1"
                                               };

            FluentTwitter.SetClientInfo(clientInfo);

            FluentTwitter.CreateRequest(clientInfo)
                .AuthenticateAs(this.username, this.password)
                .Users()
                .GetFriends()
                .AsJson()
                .CallbackTo(this.FriendsCallback)
                .RequestAsync();
        }

        private void FriendsCallback(object sender, TwitterResult twitterResult)
        {
            List<Contact> contacts = new List<Contact>();

            IEnumerable<TwitterUser> followers = twitterResult.AsUsers();

            if (followers != null)
            {
                foreach (TwitterUser user in followers)
                {
                    Contact contact = new Contact
                    {
                        Id = user.Id.ToString(),
                        FirstName = user.Name,
                        LastName = string.Empty,
                        ImageSource = user.ProfileImageUrl
                    };

                    contacts.Add(contact);
                }

                contacts.Sort((c1, c2) => string.Compare(c1.FirstName, c2.FirstName, StringComparison.Ordinal));
            }

            this.OnRetrieveContactsCompleted(contacts);
        }

        private void OnRetrieveContactsCompleted(IList<Contact> contacts)
        {
            EventHandler<DataEventArgs<IList<Contact>>> completed = this.RetrieveContactsCompleted;
            if (completed != null)
            {
                completed(this, new DataEventArgs<IList<Contact>>(contacts));
            }
        }
    }
}
